#!/bin/bash

set -e

echo "🚀 启动 Jar Monitor 应用..."
echo ""

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 检查 JAVA_HOME
if [ -z "$JAVA_HOME" ]; then
    echo -e "${YELLOW}⚠️  警告: JAVA_HOME 未设置${NC}"
    echo "尝试自动设置..."
    if command -v /usr/libexec/java_home &> /dev/null; then
        export JAVA_HOME=$(/usr/libexec/java_home -v 17 2>/dev/null || /usr/libexec/java_home)
        echo -e "${GREEN}✅ JAVA_HOME 已设置为: $JAVA_HOME${NC}"
    fi
fi

# 检查 Java 版本
if ! command -v java &> /dev/null; then
    echo -e "${RED}❌ 错误: 未找到 Java，请先安装 Java 17+${NC}"
    exit 1
fi

JAVA_VERSION=$(java -version 2>&1 | awk -F '"' '/version/ {print $2}' | awk -F '.' '{print $1}')
echo -e "${GREEN}✅ Java 版本: $JAVA_VERSION${NC}"

if [ "$JAVA_VERSION" -lt 17 ]; then
    echo -e "${RED}❌ 错误: 需要 Java 17 或更高版本，当前版本: $JAVA_VERSION${NC}"
    exit 1
fi

# 检查 Maven
if ! command -v mvn &> /dev/null; then
    echo -e "${RED}❌ 错误: 未找到 Maven，请先安装 Maven${NC}"
    exit 1
fi

echo ""

# 清理并编译
echo "📦 编译项目..."
mvn clean package -DskipTests

if [ $? -ne 0 ]; then
    echo -e "${RED}❌ 编译失败${NC}"
    exit 1
fi

echo ""
echo -e "${GREEN}✅ 编译成功！${NC}"
echo ""

# 检查是否后台运行
if [ "$1" = "background" ] || [ "$1" = "bg" ]; then
    echo "🔄 后台启动应用..."
    nohup java -jar target/jar-monitor.jar > app.log 2>&1 &
    PID=$!
    echo $PID > app.pid
    echo -e "${GREEN}✅ 应用已在后台启动${NC}"
    echo "   PID: $PID"
    echo "   日志文件: app.log"
    echo ""
    echo "📊 访问地址:"
    echo "   Web 界面: http://localhost:8080"
    echo "   Prometheus: http://localhost:8080/actuator/prometheus"
    echo ""
    echo "💡 查看日志: tail -f app.log"
    echo "💡 停止应用: kill $PID 或 ./stop.sh"
else
    echo "🚀 启动应用..."
    echo ""
    echo -e "${GREEN}📊 访问地址:${NC}"
    echo "   Web 界面: http://localhost:8080"
    echo "   Prometheus: http://localhost:8080/actuator/prometheus"
    echo "   健康检查: http://localhost:8080/actuator/health"
    echo ""
    echo -e "${YELLOW}提示: 使用 Ctrl+C 停止应用${NC}"
    echo ""
    java -jar target/jar-monitor.jar
fi
